<meta http-equiv="content-type" content="text/html; charset=utf-8">
<?php
require($_SERVER['DOCUMENT_ROOT'] . "/bootstrap.php");

if (isset($_GET['action']))
	$action = $_GET['action'];
else
	$action = 'view';

if (isset($_SESSION['email'])) {
	$islogined = 1;
} else {
	$islogined = 0;
}
$smarty->assign("islogined", $islogined);
if ($islogined == 0) {
	$smarty->assign("action", $action);
	$smarty->display('../templates/cart/index.tpl');
	die();
}

if ($action == 'add' && isset($_GET['idproduct'])) {
	if($user_loginned != "user")
	{
		echo '<script type="text/javascript">';
		echo 'alert("Chỉ có khách hàng mới được mua sản phẩm!");';
		echo 'setTimeout("top.location.href =' . "'/'" . '",0);';
		echo "</script>";
		die();
	}
	$_SESSION["error_cart_3"] = 0;
	$idproduct = $_GET['idproduct'];

	$product_buy = mysql_fetch_array(mysql_query("select * from product where idproduct=$idproduct"));
	if (($product_buy["inventory"] - $product_buy["quantity_buying"]) == 0) {
		echo '<script type="text/javascript">';
		echo 'alert("Xin lỗi bạn!\n\nSản phẩm \"' . $product_buy['productname'] . '\" đã hết hàng!");';
		echo 'setTimeout("top.location.href =' . "'/'" . '",0);';
		echo "</script>";
		die();
	}
	if (isset($_SESSION['cart'][$idproduct])) {
		// Kiểm tra SL < 3
		if ($_SESSION['cart'][$idproduct] < 3) {
			if (($_SESSION['cart'][$idproduct] + 1) <= $product_buy["inventory"]) {
				$_SESSION['cart'][$idproduct] = $_SESSION['cart'][$idproduct] + 1;
			} else {
				echo '<script type="text/javascript">';
				echo 'alert("Xin lỗi bạn!\n\nSản phẩm \"' . $product_buy['productname'] . '\" chỉ còn ' . $product_buy['inventory'] . ' cái!");';
				echo 'setTimeout("top.location.href =' . "'/cart/view'" . '",0);';
				echo "</script>";
				die();
			}
		} else {
			$_SESSION["error_cart_3"] = 1;
		}
	}

	else
		$_SESSION['cart'][$idproduct] = 1;
	header('Location: /cart/view');
	exit();
}
if ($action == 'update') {
	$error_update_str = "";
	$error_update = 0;
	if (isset($_POST)) {
		foreach ($_POST['quantity'] as $key => $value) {
			if (($value == 0) and (is_numeric($value))) {
				unset($_SESSION['cart'][$key]);
			} elseif (($value > 0) and (is_numeric($value))) {
				$product_buy = mysql_fetch_array(mysql_query("select * from product where idproduct=$key"));
				if ($value <= ($product_buy["inventory"] - $product_buy["quantity_buying"])) {
					$_SESSION['cart'][$key] = $value;
				} else {
					$error_update = 1;
					$productname = $product_buy['productname'];
					$inventory = $product_buy['inventory'] - $product_buy["quantity_buying"];
					$error_update_str = $error_update_str . "Sản phẩm \"$productname\" chỉ còn $inventory cái!\\n";
				}
			}
		}
		if ($error_update == 1) {
			$smarty->assign("error_update", $error_update);
			$smarty->assign("error_update_str", $error_update_str);
			$smarty->display('../templates/cart/index.tpl');
			die();
		}
	}
	header('Location: /cart/view');
}
if ($action == 'view') {
	// Load thông tin user
	$sql = @"SELECT * 
			FROM user
			WHERE email = '{$session_email}'";
	$query = mysql_query($sql);
	while ($row = mysql_fetch_array($query)) {
		$user_information[] = $row;
	}
	$smarty->assign("user_information", $user_information);
	// End - Load thông tin user
	$error = '';
	$count = 0;
	$ok = 1;
	if (isset($_SESSION['cart']) || (isset($_GET['order']) && isset($order_pay) && $order_pay == 1)) {
		foreach ($_SESSION['cart'] as $key => $value) {
			if (isset($key)) {
				$ok = 2;
			}
		}
		if ($ok != 2) {
			$error = "Bạn không có món hàng nào trong giỏ hàng";
		} else {
			$count = count($_SESSION['cart']);

			foreach ($_SESSION['cart'] as $key => $value) {
				$item[] = $key;
			}
			$str = implode(",", $item);
			$sql = @"SELECT * 
				 FROM product p
				 INNER JOIN
				 category c
					ON p.`idcategory` = c.`idcategory`
				 WHERE idproduct in ($str)";
			$query = mysql_query($sql);
			$total = 0;
			while ($row = mysql_fetch_array($query)) {
				$row['quantity'] = $_SESSION['cart'][$row['idproduct']];
				$cart[] = $row;
				$total += $_SESSION['cart'][$row['idproduct']] * $row['price'] * (1 - $promotion_start * $promotionbytime["percentdiscount"] / 100);
			}
			if (!isset($cart))
				$cart = '';
			$_SESSION['order_total'] = $total;
			$smarty->assign("cart", $cart);
			$smarty->assign("total", $total);
		}
		$smarty->assign("error", $error);
		$smarty->assign("count", $count);
	}
	// Xem lại đơn hàng trước khi thanh toán
	$order = 0;
	$order_pay = 0;
	if (isset($_POST['order_pay_x']))
		$order_pay = 1;
	if (isset($_GET['order']) && isset($_POST['phuongthucthanhtoan']) && $order_pay == 0) {
		if ($_GET['order'] == 1) {
			$order = 1;
		}
		$order_name = $_POST['order_name'];
		$order_phone = $_POST['order_phone'];
		$order_email = $_POST['order_email'];
		$order_address = $_POST['order_address'];
		$order_note = $_POST['order_note'];
//		$order_state = $_POST['order_state'];


		$phuongthucthanhtoan = $_POST['phuongthucthanhtoan'];
//		switch ($order_state) {
//			case 1: $order_state = 'TP. Hồ Chí Minh';
//				break;
//			case 2: $order_state = 'TP. Hà Nội';
//				break;
//			case 3: $order_state = 'TP. Huế';
//				break;
//			case 4: $order_state = 'Đà Nẵng';
//				break;
//			case 5: $order_state = 'Hải Phòng';
//				break;
//		}
//		switch ($phuongthucthanhtoan) {
//			case 1: $phuongthucthanhtoan = 'Thanh toán tiền mặt khi giao hàng tận nơi';
//				break;
//			case 2: $phuongthucthanhtoan = 'Thanh toán chuyển khoản qua ngân hàng hoặc máy ATM';
//				break;
//		}
		$order_date = gmdate("d-m-Y | H:i:s", time() + 7 * 3600);
		$order_code = "MPC" . gmdate("YmdHis", time() + 7 * 3600) . $user_information[0]['id'];
		$smarty->assign("order_name", $order_name);
		$smarty->assign("order_phone", $order_phone);
		$smarty->assign("order_email", $order_email);
		$smarty->assign("order_address", $order_address);
//		$smarty->assign("order_state", $order_state);
		$smarty->assign("order_note", $order_note);
		$smarty->assign("order_date", $order_date);
		$smarty->assign("order_code", $order_code);
		$smarty->assign("phuongthucthanhtoan", $phuongthucthanhtoan);
	}
	$smarty->assign("order", $order);

	// Submit đơn hàng
	if (isset($_GET['order']) && $order_pay == 1 && isset($cart)) {
		// kiểm tra lại lần nữa, so sánh số lượng mua <= (tồn - SL đang mua)
		$error_submit_str = "Xin lỗi bạn\\n\\n";
		$error_submit = 0;
		foreach ($cart as $cart_item) {
			$product_inventory = mysql_fetch_array(mysql_query("select * from product where idproduct={$cart_item['idproduct']}"));
			if ($cart_item["quantity"] > ($product_inventory['inventory'] - $product_inventory['quantity_buying'])) {
				$error_submit = 1;
				$productname = $cart_item['productname'];
				$inventory = $product_inventory['inventory'] - $product_inventory['quantity_buying'];
				if ($inventory == 0) {
					$error_submit_str = $error_submit_str . "Sản phẩm \"$productname\" đã hết!\\n";
				} else {
					$error_submit_str = $error_submit_str . "Sản phẩm \"$productname\" chỉ còn $inventory cái!\\n";
				}
			}
		}
		$smarty->assign("error_submit", $error_submit);
		$smarty->assign("error_submit_str", $error_submit_str);
		if ($error_submit == 1) {
			$smarty->display('../templates/cart/index.tpl');
			die();
		}
		// end - kiểm tra
		$user = mysql_fetch_array(mysql_query("select u.id from user u where u.email = '{$session_email}'"));
		$iduser = $user['id'];
		$order_date = $_POST['order_date'];
		$datetime_array = explode('|', $order_date);
		$datetime_array[0] = explode('-', $datetime_array[0]);
		$datetime_array[1] = explode(':', $datetime_array[1]);
		$order_date = mktime(trim($datetime_array[1][0]), $datetime_array[1][1], $datetime_array[1][2], $datetime_array[0][1], $datetime_array[0][0], trim($datetime_array[0][2]));
		$order_code = $_POST['order_code'];
		$order_total = $_SESSION['order_total']; // $_POST['order_total'];
		$paymethod = $_POST['phuongthucthanhtoan'];
		$order_name = $_POST['order_name'];
		$order_phone = $_POST['order_phone'];
		$order_email = $_POST['order_email'];
		$order_address = $_POST['order_address'];
		$order_note = $_POST['order_note'];

		// Xác nhận đơn hàng
		function create_confirmationcode() {
			$salt = "abchefghjkmnpqrstuvwxyz0123456789";
			srand((double) microtime() * 1000000);
			$i = 0;
			$confirmationcode = '';
			while ($i <= 19) {
				$num = rand() % 33;
				$tmp = substr($salt, $num, 1);
				$confirmationcode = $confirmationcode . $tmp;
				$i++;
			}
			return $confirmationcode;
		}

		// End
		$confirm = create_confirmationcode();
		if ($_POST['phuongthucthanhtoan'] == 1)
			$sql = @"insert into listorder(iduser,orderdatecreate,ordercode,idstatus,totalprice,orderdateship,paymethod,name,email,address,phone,note,confirm) values(
					'{$iduser}',
					'{$order_date}',
					'{$order_code}',
					1,
					'{$order_total}',
					null,
					'{$paymethod}',
					'{$order_name}',
					'{$order_email}',
					'{$order_address}',
					'{$order_phone}',
					'{$order_note}',
					'{$confirm}'
				)";
		else
			$sql = @"insert into listorder(iduser,orderdatecreate,ordercode,idstatus,totalprice,orderdateship,paymethod,name,email,address,phone,note,confirm) values(
					'{$iduser}',
					'{$order_date}',
					'{$order_code}',
					4,
					'{$order_total}',
					null,
					'{$paymethod}',
					'{$order_name}',
					'{$order_email}',
					'{$order_address}',
					'{$order_phone}',
					'{$order_note}',
					'{$confirm}'
				)";

		mysql_query($sql);
		$sql_idlist = mysql_query(@"select idlistorder from listorder where ordercode='$order_code'");
		$idorder = mysql_fetch_array($sql_idlist);
		foreach ($cart as $cart_item) {
			$price_real = $cart_item['price'] * (1 - $promotion_start * $promotionbytime['percentdiscount'] / 100);
			mysql_query(@"insert into detailorder(ordercode,idlistorder,idproduct,priece,number)value(
							'{$_POST['order_code']}',
							'{$idorder[0]}',
							'{$cart_item['idproduct']}',
							'{$price_real}',
							'{$cart_item['quantity']}'
						)");
			mysql_query(@"	update `product` 
							set `quantity_buying`=`quantity_buying`+{$cart_item['quantity']}
							where `idproduct`={$cart_item['idproduct']}
						");
		}
		unset($_SESSION['cart']);

		// Gửi confirm code cho user email đó
		// require_once('/libraries/PHPMailer/class.phpmailer.php'); đã require bên bootstrap
		define('GUSER', 'tranquocminh1112@gmail.com'); // tài khoản đăng nhập Gmail
		define('GPWD', '0244592010'); // mật khẩu cho cái mail này  

		function smtpmailer($to, $from, $from_name, $subject, $body) {
			global $error;
			$mail = new PHPMailer();  // tạo một đối tượng mới từ class PHPMailer
			$mail->IsSMTP(); // bật chức năng SMTP
			$mail->IsHTML(true);
			$mail->CharSet = "UTF-8";
			$mail->SMTPDebug = 0;  // kiểm tra lỗi : 1 là  hiển thị lỗi và thông báo cho ta biết, 2 = chỉ thông báo lỗi
			$mail->SMTPAuth = true;  // bật chức năng đăng nhập vào SMTP này
			$mail->SMTPSecure = 'ssl'; // sử dụng giao thức SSL vì gmail bắt buộc dùng cái này
			$mail->Host = 'smtp.gmail.com';
			$mail->Port = 465;
			$mail->Username = GUSER;
			$mail->Password = GPWD;
			$mail->SetFrom($from, $from_name);
			$mail->Subject = $subject;
			$mail->Body = $body;
			$mail->AddAddress($to);
			if (!$mail->Send()) {
				$error = 'Quá trình gửi email bị lỗi: ' . $mail->ErrorInfo;
				return false;
			} else {
				return true;
			}
		}

		$content = "<b>";
		$content .= "Chào bạn!<br><br>";
		$content .= "Bạn hãy click vào link sau để xác nhận hóa đơn mua hàng của bạn:<br>";
		$content .= "<a href='http://localhost/orderconfirm?ordercode=$order_code&confirmcode=$confirm'>";
		$content .= "http://localhost/orderconfirm?ordercode=$order_code&confirmcode=$confirm</a><br><br>";
		$content .= "Xin cảm ơn!";
		$content .= "</br>";
		smtpmailer($session_email, 'tranquocminh1112@gmail.com', 'www.MPCamera.com', "Xác nhận hóa đơn mua hàng mã số $order_code", $content);
		// End
	}
	$smarty->assign("order_pay", $order_pay);
	if (isset($_SESSION["error_cart_3"]))
		$smarty->assign("error_cart_3", $_SESSION["error_cart_3"]);
	else
		$smarty->assign("error_cart_3", 0);
	$_SESSION["error_cart_3"] = 0;
}
if ($action == 'delete' && isset($_GET['idproduct'])) {
	$idproduct = $_GET['idproduct'];
	if ($idproduct == 0) {
		unset($_SESSION['cart']);
	} else {
		unset($_SESSION['cart'][$_GET['idproduct']]);
	}
	header('Location: /cart/view');
	exit();
}
$smarty->assign("action", $action);
$smarty->display('../templates/cart/index.tpl');
?>